/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mindwave.theoracle;

import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Icon;
import javax.swing.ImageIcon;

/**
 *
 * @author MarcoJ
 */
public class MindWaveTheOracle {
    
    
    private static long  AbsoluteTime = 0;
    
    
    private static double p3time = 0;
    private static int imgtmp = -1;
    private static boolean p3 = false;
    private static double delay2 = 175;
    private static double delay1 = 250;
    private static boolean firstTime = true;
     

    public static int getRandomNumberFrom(int min, int max) {
        Random foo = new Random();
        int randomNumber = foo.nextInt((max + 1) - min) + min;

        return randomNumber;

    }
    
    public static experienceBean p3checker(experienceBean inp) {

        if (firstTime == true) {
            p3time = AbsoluteTime;
            imgtmp = inp.getFigure().getCode();
            firstTime = false;
        }
        if (imgtmp != inp.getFigure().getCode() && p3 == false) {
            p3time = inp.getTime();
            p3 = true;
        }
        if (imgtmp != inp.getFigure().getCode() && p3 == true) {
            
            Figure img = Figure.getFigure(imgtmp);
            if((inp.getTime()-p3time)>delay2){
                p3 = false;
                imgtmp = inp.getFigure().getCode();
            }
            inp.setFigure(img);
            inp.setImage(img.name());
            inp.setP3(2);
            return inp;

        } else {
          if((inp.getTime()-p3time)>delay1){
              inp.setP3(1);   
            }   
         
        return inp;
        
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(final String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            Grafics g = new Grafics(2);
            long time = 0;
            ReadMindWave mind = new ReadMindWave();
            Writer csv;
            NeuralOracle nno = new NeuralOracle();
            
            public void run() {
                Thread a = new Thread(new Runnable() {
                    public void run() {

                        g.setVisible(true);
                    }
                });
                Thread b = new Thread(new Runnable() {
                    public void run() {
                        while (time == 0) {
                            //System.out.println("Attendo");
                        }
                        csv = new Writer(g.getName());
                        System.out.println(args);
                        mind.run();

                    }
                });
                Thread c;
                c = new Thread(new Runnable() {
                    public void run() {
                        List<experienceBean> tmp;
                        String[] dupl = new String[17];
                        while (mind.isStop() == false) {
                            if ((tmp = mind.freeQueuque()) != null) {
                                for (int i = 0; i < tmp.size(); i++) {
                                    experienceBean p3temp = p3checker(tmp.get(i));                                    
                                    String[] tempArr = p3temp.getStringArray();
                                    if (!Arrays.equals(tempArr, dupl)) {
                                        csv.writeArray(p3temp);
                                        if (args != null) {
                                            nno.addDataRowTraining(p3temp,Figure.Cerchio);      // FIGURA DA INSERIRE MANUALMENTE
                                        }   
                                    }
                                    dupl = tempArr;
                                }
                            }
                        }
                        csv.stopWriting();
                        System.out.println("Learning...");
                        nno.learn();
                        System.out.println("Saving...");
                        nno.saveNN(g.getName());
                        
                        if(args!=null){
                            System.out.println("Fine Training");
                            g.dispose();
                        } else {
                            
                        }
                            
                    }
                });


                Thread p = new Thread(new Runnable() {
                    @Override
                    public void run() {


                        boolean active = false;
                        int temp = 6;

                        while (1 != 0) {

                            int random = getRandomNumberFrom(1, 4);

                            while (random == temp) {
                                random = getRandomNumberFrom(1, 4);
                            }
                            temp = random;

                            if (g.isReady()) {
                                if (!active) {
                                    time = System.currentTimeMillis();
                                    active = true;
                                }


                                Icon imageA = new ImageIcon(getClass().getResource("images/immagine" + random + "A.jpg"));
                                Icon imageS = new ImageIcon(getClass().getResource("images/immagine" + random + "S.jpg"));

                                if (time != 0 & ((System.currentTimeMillis() - time) / 1000) >= 60) {
                                    break;
                                }

                                g.setImageFig(random, imageA);
                                mind.setImageFocus(random);

                                try {
                                    Thread.sleep(300);


                                } catch (InterruptedException ex) {
                                    Logger.getLogger(MindWaveTheOracle.class.getName()).log(Level.SEVERE, null, ex);
                                }

                                g.setImageFig(random, imageS);
                                mind.setImageFocus(0);


                            }
                        }

                        mind.stop(true);

                        try {
                            Thread.sleep(40);


                        } catch (InterruptedException ex) {
                            Logger.getLogger(MindWaveTheOracle.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        
                    }
                });
                a.start();
                b.setPriority(Thread.MAX_PRIORITY);
                b.start();

                p.start();

                c.start();
            }
        });


    } // TODO code application logic here
}
